package com.hdu.controller;

import com.hdu.common.Result;
import com.hdu.common.ResultCode;
import com.hdu.exception.CustomException;
import com.hdu.service.URLService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.hdu.util.RedisConstants.Visit_Count_Key;

@RestController
@RequestMapping("/visited")
public class VisitedUrlController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    URLService urlService;


    @GetMapping("/page/{url}")
    public Result<Integer> countTime(@PathVariable String url){
        Integer counts;
        if (url.isEmpty()){
            throw new CustomException("url为空，错误！");
        }
        String str = stringRedisTemplate.opsForValue().get(Visit_Count_Key + url);
        if (str==null) {
            counts = urlService.getVisitedUrlCountsByUrl(url);
            return new Result<>(ResultCode.SUCCESS,counts);
        }

        return new Result<>(ResultCode.SUCCESS,Integer.parseInt(str));
    }

    @GetMapping("/count/{url}")
    public Result<String> TimeIncrement(@PathVariable String url){
        if (url.isEmpty()){
            throw new CustomException("url为空，错误！");
        }
//        String test = stringRedisTemplate.opsForValue().get("test1");
//        System.out.println(test);
//        stringRedisTemplate.opsForValue().set("test1","1");
        if(!urlService.incrementVisitedCount(url)){
            throw new CustomException("url发生错误！");
        }

        return new Result<>(ResultCode.SUCCESS);

    }
}
